package com.example.onion.hxchat.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.onion.hxchat.adapter.SearchFriendDisplayAdapter;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.util.GsonUtil;
import com.example.onion.hxchat.util.HttpUtils;
import com.example.superyi.myteam.R;

import java.io.IOException;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;

/**
 * @author:onion
 * @data: 2020/7/26
 */
public class SearchFriendActivity extends AppCompatActivity {

    private String searchName;
    private RecyclerView mRecyclerView;
    private SearchFriendDisplayAdapter searchFriendDisplayAdapter;
    private Toolbar toolbar;

//    @SuppressLint("HandlerLeak")
//    private Handler handler = new Handler() {
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case SearchFriendThread.SEARCH_IS_FINISH:
//                    List<User> list = (List<User>) msg.obj;
//                    break;
//                case SearchFriendThread.SEARCH_IS_FAILED:
//                    break;
//                default:
//                    break;
//            }
//        }
//    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_friend_activity);
        ininData();
        initRecyclerView();
        toolbar = findViewById(R.id.search_friend_toolbar_wc);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        searchUserInfoFromNet();
    }


    private void ininData() {
        searchName = getIntent().getStringExtra("searchFriendUserName");
    }

    private void initRecyclerView() {


        //获取RecyclerView
        mRecyclerView = findViewById(R.id.search_friend_recyclerview_wc);
        //创建adapter
        searchFriendDisplayAdapter = new SearchFriendDisplayAdapter();
        //适配器只负责得到数据，跳转页面由从适配器获取到数据的Activity或者Fragment（本fragment页面）去选择跳转到哪个页面
        searchFriendDisplayAdapter.setDataGetterListener(infoBean -> {//infoBean是通过回到机制从适配器中得到的数据
            Intent intent = new Intent(SearchFriendActivity.this, ScanUserActivity.class);
            intent.putExtra("scanUserName", infoBean.getUserName());//传递用户昵称至浏览页面(加前缀scan)
            intent.putExtra("scanUserId", infoBean.getUserId());//传递用户id至浏览页面(加前缀scan)
            intent.putExtra("scanUserSpy", infoBean.getUserSpy());//传递用户专业spy至浏览页面(加前缀scan)
            startActivity(intent);
        });
        //给RecyclerView设置adapter
        mRecyclerView.setAdapter(searchFriendDisplayAdapter);
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        mRecyclerView.setLayoutManager(new LinearLayoutManager(SearchFriendActivity.this, LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(SearchFriendActivity.this, DividerItemDecoration.VERTICAL));
    }



//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.toolbar_user_detail_menu, menu);
//        return true;
//    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home://系统自带的返回箭头的资源id
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }





    private void searchUserInfoFromNet() {
        HttpUtils httpUtils = HttpUtils.getInstance();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("userName", searchName);
        FormBody formBody = builder.build();
        httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/GetUserInfoByNameServlet", formBody, new HttpUtils.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {

            }

            @Override
            public void onSuccess(Request request, String result) {
                List<User> list = GsonUtil.getObjectList(result, User.class);
                searchFriendDisplayAdapter.setmList(list);
                notifyDataChanged(SearchFriendActivity.this,searchFriendDisplayAdapter);
            }
        });
    }

    /**
     *
     * @param ctx
     * @param adapter
     */
    public static void notifyDataChanged(final Activity ctx,SearchFriendDisplayAdapter adapter) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            adapter.notifyDataSetChanged();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }
}